import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

// 设置vueRouter跳转同一路由不报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function(location) {
  return originalPush.call(this, location).catch(() => {})
}
Vue.use(VueRouter)

const routes = [
  // 路由重定向
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    meta: { activeNum: 0, isShowTabbar: true },
    component: Home,
    children: [
      {
        path: '/home/searchPopup',
        name: 'SearchPopup',
        component: () => import(/* webpackChunkName: "SearchPopup" */ '../views/SearchPopup.vue')
      }
    ]
  },
  {
    path: '/category',
    name: 'Category',
    meta: { activeNum: 1, isShowTabbar: true },
    component: () => import(/* webpackChunkName: "Category" */ '../views/Category.vue')
  },
  {
    path: '/topic',
    name: 'Topic',
    meta: { activeNum: 2, isShowTabbar: true },
    component: () => import(/* webpackChunkName: "Topic" */ '../views/Topic.vue')
  },
  {
    path: '/cart',
    name: 'Cart',
    meta: { activeNum: 3, isShowTabbar: true },
    component: () => import(/* webpackChunkName: "Cart" */ '../views/Cart.vue')
  },
  {
    path: '/user',
    name: 'User',
    meta: { activeNum: 4, isShowTabbar: true },
    component: () => import(/* webpackChunkName: "User" */ '../views/User.vue')
  },
  {
    path: '/productDetail',
    name: 'ProductDetail',
    component: () => import(/* webpackChunkName: "ProductDetail" */ '../views/ProductDetail.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫(路由拦截器)
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.path === '/cart') {
    if (token) {
      next()
    } else {
      Vue.prototype.$toast('请先登录')
      next('/user')
    }
  }
  next()
})

export default router
